import subprocess
import fcntl
import os
import time

def nonBlockRead(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.readline()
    except:
        return ''

print('One line at a time:')
proc = subprocess.Popen('python3 sysreadline.py', bufsize=1,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    s = str(i) + '\n'
    proc.stdin.write(bytes(s, "ascii"))
    proc.stdin.flush()
    output = nonBlockRead(proc.stdout)
    print('out : '+str(output))
    time.sleep(1)
remainder = proc.communicate()[0]
print(remainder)





print('')
print('All output at once:')
proc = subprocess.Popen('python3 sysreadline.py',
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
for i in range(10):
    s = str(i) + '\n'
    proc.stdin.write(s.encode(encoding='ascii'))


output = proc.communicate()[0]
print(output)